<script lang="ts" setup>
import type { InfoGroupApi } from '#/api/spa/group';

import { useVbenModal } from '@vben/common-ui';
import { message, Tabs, Checkbox, Input, Textarea, Select,RadioGroup,CheckboxGroup, DatePicker } from 'ant-design-vue';
  import InfoStoreForm from './info-store-form.vue'

import { computed, ref } from 'vue';
import { $t } from '#/locales';
import { useVbenForm } from '#/adapter/form';
import { getInfoGroup, createInfoGroup, updateInfoGroup } from '#/api/spa/group';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<InfoGroupApi.InfoGroup>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['集团信息'])
    : $t('ui.actionTitle.create', ['集团信息']);
});


  /** 子表的表单 */
  const subTabsName = ref('infoStore')
      const infoStoreFormRef = ref<InstanceType<typeof InfoStoreForm>>()

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
            // 校验子表单
                 modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as InfoGroupApi.InfoGroup;
            // 拼接子表的数据
            data.infoStores = infoStoreFormRef.value?.getData();
    try {
      await (formData.value?.id ? updateInfoGroup(data) : createInfoGroup(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success( $t('ui.actionMessage.operationSuccess') );
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    let data = modalApi.getData<InfoGroupApi.InfoGroup>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getInfoGroup(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values
    formData.value = data;
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
          <!-- 子表的表单 -->
      <Tabs v-model:active-key="subTabsName">
          <Tabs.TabPane key="infoStore" tab="门店" force-render>
            <InfoStoreForm ref="infoStoreFormRef" :group-id="formData?.id" />
          </Tabs.TabPane>
      </Tabs>
  </Modal>
</template>